package com.example.tenant.config;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ExcelExportUtil {

    public static <T> void exportExcelToFile(IService<T> service, Long tenantId, Class<T> entityClass, FileOutputStream outputStream) {

        try (ExcelWriter excelWriter = EasyExcel.write(outputStream, entityClass).build()) {
            // 创建工作表
            WriteSheet writeSheet = EasyExcel.writerSheet("sheet").build();
            // 写入数据
            List<T> dataList = fetchData(service, tenantId);
            excelWriter.write(dataList, writeSheet);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static <T> List<T> fetchData(IService<T> service, Long tenantId) {
        if (tenantId == null) {
            return service.list();
        }
        // 构建查询条件
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("tenant_id", tenantId);

        return service.list(queryWrapper);
    }
}